package com.siwei.mes.service.laboratory.factory.material.cement;

import com.alibaba.fastjson.JSONObject;
import com.siwei.mes.common.util.JsonUtils;
import com.siwei.mes.common.util.NullUtils;
import com.siwei.mes.entity.experiment.CheckBatchConfig;
import com.siwei.mes.entity.experiment.Experiment;
import com.siwei.mes.entity.experiment.ExperimentDetail;
import com.siwei.mes.entity.experiment.cement.CementAdx;
import com.siwei.mes.entity.laboratory.DataDefaultUc;
import com.siwei.mes.entity.laboratory.cement.DataSnAdx;
import com.siwei.mes.entity.system.TestProjectInfo;
import com.siwei.mes.entity.system.TestProjectSpecConfig;
import com.siwei.mes.enums.TestProjectEnum;
import com.siwei.mes.mapper.experiment.ExperimentDetailMapper;
import com.siwei.mes.mapper.laboratory.CementLaboratoryMapper;
import com.siwei.mes.mapper.laboratory.UploadLaboratoryMapper;
import com.siwei.mes.service.laboratory.factory.LaboratoryAbstractService;
import com.siwei.mes.service.laboratory.factory.entity.LaboratoryDownloadVo;
import com.siwei.mes.service.laboratory.factory.material.MaterialLaboratoryFactory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 水泥-安定性
 *
 * @Description: 水泥-安定性
 * @Version: 1.0
 * @author: mlchen
 * @date: 2025/3/29 16:31
 */
@Service
public class CementAdxFactory extends LaboratoryAbstractService implements MaterialLaboratoryFactory {
    private static final Logger log = LoggerFactory.getLogger("laboratory");

    @Resource
    private CementLaboratoryMapper cementLaboratoryMapper;
    @Resource
    private UploadLaboratoryMapper uploadLaboratoryMapper;
    @Resource
    private ExperimentDetailMapper experimentDetailMapper;

    private final TestProjectEnum testProjectEnum = TestProjectEnum.CEMENT_PARAM_ADX;

    @Override
    public void processUpload(JSONObject objJson, String sampleNo, Experiment experiment, List<CheckBatchConfig> batchConfigList, List<TestProjectInfo> testProjectInfoList, List<TestProjectSpecConfig> testProjectSpecConfigList, ExperimentDetail detail, String samId) {
        log.info("开始上传到协会数据库：【水泥-{}】", testProjectEnum.getName());
        //将json转成对象
        CementAdx cementAdx = objJson.toJavaObject(CementAdx.class);

        if (cementAdx == null) {
            log.info("水泥-【{}】数据为空，跳过上传！objJson：{}", testProjectEnum.getName(), objJson);
            return;
        }

        //赋值dateDefalutUC
        //存储协会需要做的项目集合
        Set<String> set = new HashSet<>();

        for (TestProjectInfo testProjectInfo : testProjectInfoList) {
            if (detail.getTestProjectCode() != null && testProjectInfo.getTestCode() != null && testProjectInfo.getTestCode().equals(detail.getTestProjectCode())) {
                if (testProjectInfo.getParameterName() != null && !testProjectInfo.getParameterName().isEmpty()) {
                    //添加进协会需要做的项目集合
                    set.addAll(Arrays.asList(testProjectInfo.getParameterName().split(",")));
                }
            }
        }


        if (cementAdx.getLsf() != null && cementAdx.getLsf().getJl() != null) {
            //创建协会水泥对象
            DataSnAdx dataSnAdx = new DataSnAdx();

            dataSnAdx.setTestMethod("雷氏法");
            dataSnAdx.setConclusion(cementAdx.getLsf().getJl());
            dataSnAdx.setS1(NullUtils.ifNull(cementAdx.getLsf().getJza()));
            dataSnAdx.setS2(NullUtils.ifNull(cementAdx.getLsf().getJzc()));
            dataSnAdx.setS3(NullUtils.ifNull(cementAdx.getLsf().getZjjl()));
            dataSnAdx.setS4(NullUtils.ifNull(cementAdx.getLsf().getJza1()));
            dataSnAdx.setS5(NullUtils.ifNull(cementAdx.getLsf().getJzc1()));
            dataSnAdx.setS6(NullUtils.ifNull(cementAdx.getLsf().getZjjl1()));
            dataSnAdx.setS7(NullUtils.ifNull(cementAdx.getLsf().getPjz()));
            //获取标准值
            for (CheckBatchConfig projectInfo : batchConfigList) {
                if (projectInfo.getTestProjectCode() != null && projectInfo.getTestProjectCode().equals(TestProjectEnum.CEMENT_PARAM_ADX.getCode())) {
                    dataSnAdx.setSt1(NullUtils.ifNull(projectInfo.getCheckValueUnit()));
                }
            }

            //设置公共属性
            super.setCommonProperties(sampleNo, experiment, dataSnAdx, "水泥", cementAdx.getJcrq(), detail);

            //根据样品编码查询水泥安定性
            DataSnAdx data_jgcl_sn_adxBySampleNo = cementLaboratoryMapper.findDATA_JGCL_SN_ADXBySampleNo(sampleNo);
            //查询没值说明需要  新增水泥安定性
            if (data_jgcl_sn_adxBySampleNo == null) {
                cementLaboratoryMapper.addDATA_JGCL_SN_ADX(dataSnAdx);
            } else {
                //修改水泥安定性值
                cementLaboratoryMapper.updateDATA_JGCL_SN_ADX(dataSnAdx);
            }


            for (String str : set) {
                DataDefaultUc defaultUc = new DataDefaultUc();

                Map<String, Object> itemParameter = uploadLaboratoryMapper.findItemParameter(str, samId);

                if (itemParameter == null || itemParameter.get("ParameterID") == null) {
                    log.error("未查询到对应的材料：value = " + str + "SampleID =" + samId);
                    continue;
                }
                String parameterID = itemParameter.get("ParameterID").toString();

                String jcrq = cementAdx.getJcrq();

                defaultUc.setConclusion(cementAdx.getLsf().getJl());
                defaultUc.setUcResultValue(cementAdx.getLsf().getJl());

                if(StringUtils.isNotBlank(cementAdx.getLsf().getJl()) && cementAdx.getLsf().getJl().equals("合格")){
                    defaultUc.setUcTestValue("0");
                }else{
                    defaultUc.setUcTestValue("1");
                }

                //获取标准值
                for (CheckBatchConfig projectInfo : batchConfigList) {
                    if (projectInfo.getTestProjectCode() != null && projectInfo.getTestProjectCode().equals(TestProjectEnum.CEMENT_PARAM_ADX.getCode())) {
                        defaultUc.setUcUnit(NullUtils.ifNull(projectInfo.getCheckValueUnit()));
                    }
                }


                defaultUc.setUcStandardValue("雷氏法");

                //赋值
                super.setDefUc(defaultUc, experiment, "水泥检测室", sampleNo, jcrq, detail);

                defaultUc.setUcParameterID(parameterID);//项目id

                //新增或修改DataDefaultUc
                super.insertOrUpdateDataDefaultUc(sampleNo, parameterID, defaultUc);
            }

        }else {
            if (cementAdx.getSbf() == null || cementAdx.getSbf().getJl() == null) {
                log.info("水泥-【{}】中试饼法数据为空，跳过上传！objJson：{}", testProjectEnum.getName(), objJson);
                return;
            }

            //创建协会水泥对象
            DataSnAdx dataSnAdx = new DataSnAdx();

            dataSnAdx.setTestMethod("饼法");
            dataSnAdx.setConclusion(cementAdx.getSbf().getJl());

            //设置公共属性
            super.setCommonProperties(sampleNo, experiment, dataSnAdx, "水泥", cementAdx.getJcrq(), detail);

            //根据样品编码查询水泥安定性
            DataSnAdx data_jgcl_sn_adxBySampleNo = cementLaboratoryMapper.findDATA_JGCL_SN_ADXBySampleNo(sampleNo);
            //查询没值说明需要  新增水泥安定性
            if (data_jgcl_sn_adxBySampleNo == null) {
                cementLaboratoryMapper.addDATA_JGCL_SN_ADX(dataSnAdx);
            } else {
                //修改水泥安定性值
                cementLaboratoryMapper.updateDATA_JGCL_SN_ADX(dataSnAdx);
            }


            for (String str : set) {
                DataDefaultUc defaultUc = new DataDefaultUc();

                Map<String, Object> itemParameter = uploadLaboratoryMapper.findItemParameter(str, samId);

                if (itemParameter == null || itemParameter.get("ParameterID") == null) {
                    log.error("未查询到对应的材料：value = " + str + "SampleID =" + samId);
                    continue;
                }
                String parameterID = itemParameter.get("ParameterID").toString();

                String jcrq = cementAdx.getJcrq();

                defaultUc.setConclusion(cementAdx.getSbf().getJl());
                defaultUc.setUcResultValue(cementAdx.getSbf().getJl());

                if(StringUtils.isNotBlank(cementAdx.getSbf().getJl()) && cementAdx.getSbf().getJl().equals("合格")){
                    defaultUc.setUcTestValue("0");
                }else{
                    defaultUc.setUcTestValue("1");
                }

                //获取标准值
                for (CheckBatchConfig projectInfo : batchConfigList) {
                    if (projectInfo.getTestProjectCode() != null && projectInfo.getTestProjectCode().equals(TestProjectEnum.CEMENT_PARAM_ADX.getCode())) {
                        defaultUc.setUcUnit(NullUtils.ifNull(projectInfo.getCheckValueUnit()));
                    }
                }


                defaultUc.setUcStandardValue("饼法");

                //赋值
                super.setDefUc(defaultUc, experiment, "水泥检测室", sampleNo, jcrq, detail);

                defaultUc.setUcParameterID(parameterID);//项目id

                //新增或修改DataDefaultUc
                super.insertOrUpdateDataDefaultUc(sampleNo, parameterID, defaultUc);
            }


        }
    }

    @Override
    public LaboratoryDownloadVo processDownload(String sampleNo, Experiment experiment, ExperimentDetail detail, Map<String, String> parameterMap, String samId, List<TestProjectInfo> testProjectInfoList) {
        log.info("开始下载协会数据到品控：【水泥-{}】", testProjectEnum.getName());
        JSONObject objJson = detail.getObjJson();
        //将json转成对象
        CementAdx cementAdx = objJson.toJavaObject(CementAdx.class);
        if (cementAdx == null) {
            log.info("【水泥-{}】数据为空，跳过下载！objJson：{}", testProjectEnum.getName(), objJson);
            return null;
        }
        DataSnAdx map = cementLaboratoryMapper.findDATA_JGCL_SN_ADXBySampleNo(sampleNo);

        if (map == null) {
            log.info("查询协会【水泥-{}】信息为空。跳过下载！sampleNo：【{}】", testProjectEnum.getName(), sampleNo);
            return null;
        }

        if("饼法".equals(map.getTestMethod())){
            //试饼法
            CementAdx.Sbf sbf = cementAdx.getSbf();

            if (sbf == null) {
                log.info("品控【水泥-{}】试饼法为空。跳过下载！objJson：【{}】", testProjectEnum.getName(), objJson);
                return null;
            }

            if (map.getConclusion() != null) {
                sbf.setJl(map.getConclusion());
                if ("合格".equals(map.getConclusion())) {
                    sbf.setYwlw("否");
                    sbf.setSfwq("否");
                } else {
                    sbf.setYwlw("是");
                    sbf.setSfwq("是");
                }
            }

            if (map.getDetectonDate() != null) {
                Date detectonDate = map.getDetectonDate();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String strDate = sdf.format(detectonDate);
                cementAdx.setJcrq(strDate);
            }
        }else {
            CementAdx.Lsf lsf = cementAdx.getLsf();
            if (lsf == null) {
                log.info("品控【水泥-{}】雷氏法为空。跳过下载！objJson：【{}】", testProjectEnum.getName(), objJson);
                return null;
            }
            if(map.getS1() != null){
                lsf.setJza(map.getS1());
            }
            if(map.getS2() != null){
                lsf.setJzc(map.getS2());
            }
            if(map.getS3() != null){
                lsf.setZjjl(map.getS3());
            }
            if(map.getS4() != null){
                lsf.setJza1(map.getS4());
            }
            if(map.getS5() != null){
                lsf.setJzc1(map.getS5());
            }
            if(map.getS6() != null){
                lsf.setZjjl1(map.getS6());
            }
            if(map.getS7() != null){
                lsf.setPjz(map.getS7());
            }
            if (map.getConclusion() != null) {
                lsf.setJl(map.getConclusion());
            }
        }


        //对象转json
        JSONObject jsonObject = JsonUtils.beanToObject(cementAdx);

        //重新赋值
        detail.setObjJson(jsonObject);

        detail.setEquipment(NullUtils.ifNull(map.getEquipment()));
        detail.setTemperature(NullUtils.ifNull(map.getTemperature()));
        detail.setHumidness(NullUtils.ifNull(map.getHumidity()));
        detail.setExperimentGist(NullUtils.ifNull(map.getDetectonRuleCode()));
        detail.setJudgeGist(NullUtils.ifNull(map.getAccessRuleCode()));


        if (parameterMap.containsKey(detail.getTestProjectCode())) {
            detail.setStatus(parameterMap.get(detail.getTestProjectCode()));
        }

        //修改品控试验数据
        experimentDetailMapper.updateByPrimaryKeySelective(detail);

        return new LaboratoryDownloadVo().setEquipment(detail.getEquipment())
                .setJudgeGist(detail.getJudgeGist())
                .setExperimentGist(detail.getExperimentGist())
                .setTemperature(detail.getTemperature())
                .setHumidness(detail.getHumidness());
    }
}